package it.unipd.fbaron.mind_reader_squared.activities;

import it.unipd.fbaron.mind_reader_squared.R;
import it.unipd.fbaron.mind_reader_squared.model.SymbolDAO;
import it.unipd.fbaron.mind_reader_squared.model.SymbolLogic;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

import android.app.Activity;
import android.app.Fragment;
import android.content.ContentValues;
import android.content.Intent;
import android.content.res.TypedArray;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.MediaColumns;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;

public class OptionsFragment extends Fragment {

	private OnOptionsEventListener listener;

	private boolean isNewSymbol;
	private int currTabIndex;

	AsyncTask<Integer, Void, Camera> t;
	private static Camera camera;
	private boolean isPreviewOpen;

	final static int RECORDING_INTENT = 1;
	
	//Spinner variables
	private boolean isParentSpinnerSelectable = false;

	private EditText title;
	private ImageView image;
	private EditText tts;
	private RadioButton soundButton1;
	private RadioButton soundButton2;
	private ImageButton soundPlay;
	private ImageButton soundRecord;
	private CheckBox m1;
	private TextView pos1;
	private TextView clicks1;
	private TextView pos1Label;
	private TextView clicks1Label;
	private CheckBox m2;
	private TextView pos2;
	private TextView clicks2;
	private TextView pos2Label;
	private TextView clicks2Label;
	private TextView parentLabel;
	private TextView parent;
	private Spinner parentSpinner;
	private ImageButton moveUp;
	private ImageButton moveDown;
	private ImageButton delete;
	private ImageButton save;
	private Button startPreview;
	private SurfaceView surfaceView;
	private Button stopPreview;
	private Button loadPicture;
	private Button loadDefaultPicture;
	private TextView moveUpLabel;
	private TextView moveDownLabel;
	private TextView deleteLabel;

	/*
	 * Callback interface to communicate with ManageSymbol activity
	 */
	public interface OnOptionsEventListener {
		public void onSave(SymbolDAO symbol);

		public void onDelete(int symbol_id);

		public void onMoveUp(int symbol_id);

		public void onMoveDown(int symbol_id);
		
		public void onChangeParent(int symbol_id, int parent_id);

		public void onModify();

		public void onLoadImage();
	}

	/*
	 * To ensure that the host activity implements this interface, fragment A's
	 * onAttach() callback method (which the system calls when adding the
	 * fragment to the activity) instantiates an instance of
	 * OnArticleSelectedListener by casting the Activity that is passed into
	 * onAttach()
	 */
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			listener = (OnOptionsEventListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement OnOptionsEventListener");
		}
	}

	/*
	 * Create a new instance of DetailsFragment, initialized to show the text at
	 * 'index'.
	 */
	public static OptionsFragment newInstance(SymbolDAO symbol) {
		OptionsFragment f = new OptionsFragment();

		Bundle args = new Bundle();
		args.putInt("id", symbol.getId());
		args.putString("name", symbol.getName());
		args.putInt("img_res", symbol.getImageResource());
		args.putString("img_path", symbol.getImagePath());
		args.putString("txt", symbol.getText());
		args.putInt("parent", symbol.getParent());
		args.putBoolean("m1", symbol.isM1());
		args.putBoolean("m2", symbol.isM2());
		args.putInt("m1_pos", symbol.getM1Pos());
		args.putInt("m2_pos", symbol.getM2Pos());
		args.putString("sound_path", symbol.getSoundPath());
		args.putInt("profile", symbol.getProfileId());
		args.putInt("clicks_m1", symbol.getClicksM1());
		args.putInt("sound_choise", symbol.getSoundChoise());
		args.putInt("clicks_m2", symbol.getClicksM2());
		f.setArguments(args);

		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		isPreviewOpen = false;
	}

	@Override
	public void onPause() {
		super.onDestroy();

		if (camera != null) {
			camera.release();
			camera = null;
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		isPreviewOpen = false;
	}

	/**
	 * Insert on xml layout some informations taked from database and return the
	 * options view
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		// Inflate the layout for this fragment
		View v = inflater.inflate(R.layout.options_fragment_layout, container,
				false);

		// Control if it's a new symbol
		if (getArguments().getInt("id") < 1) {
			isNewSymbol = true;
		} else {
			isNewSymbol = false;
		}
		
		// Get tab index from ManageSymbolActivity
		currTabIndex = ((ManageSymbolActivity)getActivity()).getCurrTabIndex();

		// Title
		title = (EditText) v.findViewById(R.id.options_title);
		title.setText(getArguments().getString("txt"));

		// Image
		image = (ImageView) v.findViewById(R.id.options_image);
		image.setImageDrawable(((ManageSymbolActivity) getActivity())
				.getSymbolImage(getArguments().getInt("img_res"),
						getArguments().getString("img_path")));

		// Title Edit
		tts = (EditText) v.findViewById(R.id.options_edit_title);
		tts.setText(title.getText());

		// Radio Buttons
		soundButton1 = (RadioButton) v
				.findViewById(R.id.options_radio_button_1);
		soundButton2 = (RadioButton) v
				.findViewById(R.id.options_radio_button_2);
		soundPlay = (ImageButton) v.findViewById(R.id.options_play);
		soundRecord = (ImageButton) v.findViewById(R.id.options_register);
		if (getArguments().getInt("sound_choise") == 0) {
			soundButton1.setChecked(true);
			soundButton2.setChecked(false);
		} else {
			soundButton1.setChecked(false);
			soundButton2.setChecked(true);
			soundRecord.setVisibility(View.VISIBLE);
			if (getArguments().getString("sound_path").equals(""))
				tts.setText(R.string.not_registered);
			else
				tts.setText(R.string.registered);
		}

		// M1
		m1 = (CheckBox) v.findViewById(R.id.options_m1);
		pos1 = (TextView) v.findViewById(R.id.options_pos_m1);
		clicks1 = (TextView) v.findViewById(R.id.options_click_m1);
		pos1Label = (TextView) v.findViewById(R.id.options_pos_m1_label);
		clicks1Label = (TextView) v.findViewById(R.id.options_click_m1_label);
		m1.setClickable(false);
		if (getArguments().getBoolean("m1")) {
			m1.setChecked(true);

			// Pos M1
			pos1Label.setText(pos1Label.getText() + ":");
			pos1.setText(String.valueOf(getArguments().getInt("m1_pos")));

			// Number of clicks M1
			clicks1Label.setText(clicks1Label.getText() + ":");
			clicks1.setText(String.valueOf(SymbolLogic.getInstance(
					((ManageSymbolActivity) getActivity()).dbHelper).getClicks(
					getArguments().getInt("id"), true)));
		} else {
			pos1.setVisibility(View.INVISIBLE);
			clicks1.setVisibility(View.INVISIBLE);
			pos1Label.setVisibility(View.INVISIBLE);
			clicks1Label.setVisibility(View.INVISIBLE);
		}

		if (isNewSymbol) {
			m1.setClickable(true);
			// M1 listener
			m1.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {
					if (isChecked) {
						int newPos = SymbolLogic
								.getInstance(
										((ManageSymbolActivity) getActivity()).dbHelper)
								.getNumM1Symbols(
										((ManageSymbolActivity) getActivity())
												.getProfileId());
						getArguments().putInt("m1_pos", newPos);
						getArguments().putBoolean("m1", true);
						pos1.setText(String.valueOf(newPos));
						clicks1.setText(String.valueOf(0));
						pos1.setVisibility(View.VISIBLE);
						clicks1.setVisibility(View.VISIBLE);
						pos1Label.setVisibility(View.VISIBLE);
						clicks1Label.setVisibility(View.VISIBLE);
					} else {
						getArguments().putInt("m1_pos", -1);
						getArguments().putBoolean("m1", false);
						pos1.setVisibility(View.INVISIBLE);
						clicks1.setVisibility(View.INVISIBLE);
						pos1Label.setVisibility(View.INVISIBLE);
						clicks1Label.setVisibility(View.INVISIBLE);
					}
					listener.onModify();
					setModified(true);
				}
			});
		}

		// M2
		m2 = (CheckBox) v.findViewById(R.id.options_m2);
		pos2 = (TextView) v.findViewById(R.id.options_pos_m2);
		clicks2 = (TextView) v.findViewById(R.id.options_click_m2);
		pos2Label = (TextView) v.findViewById(R.id.options_pos_m2_label);
		clicks2Label = (TextView) v.findViewById(R.id.options_click_m2_label);
		parent = (TextView) v.findViewById(R.id.options_parent);
		parentLabel = (TextView) v.findViewById(R.id.options_parent_label);
		m2.setClickable(false);
		if (getArguments().getBoolean("m2")) {
			m2.setChecked(true);

			// Pos M2
			pos2Label.setText(pos2Label.getText() + ":");
			pos2.setText(String.valueOf(getArguments().getInt("m2_pos")));

			// Number of clicks M2
			clicks2Label.setText(clicks2Label.getText() + ":");
			clicks2.setText(String.valueOf(SymbolLogic.getInstance(
					((ManageSymbolActivity) getActivity()).dbHelper).getClicks(
					getArguments().getInt("id"), false)));
			
			// Parent name will be loaded after
			parentLabel.setText(parentLabel.getText() + ":");
			
		} else {
			pos2.setVisibility(View.INVISIBLE);
			clicks2.setVisibility(View.INVISIBLE);
			pos2Label.setVisibility(View.INVISIBLE);
			clicks2Label.setVisibility(View.INVISIBLE);
			parent.setVisibility(View.GONE);
			parentLabel.setVisibility(View.INVISIBLE);
		}

		if (isNewSymbol) {
			m2.setClickable(true);
			// M2 listener
			m2.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {
					if (isChecked) {
						//Update options instance of the symbol
						int new_pos = SymbolLogic.getInstance(((ManageSymbolActivity)getActivity()).dbHelper).getSymbolNumChildren(0);
						getArguments().putInt("m2_pos", new_pos);
						getArguments().putBoolean("m2", true);
						pos2.setText(String.valueOf(new_pos));
						clicks2.setText(String.valueOf(0));
						pos2.setVisibility(View.VISIBLE);
						clicks2.setVisibility(View.VISIBLE);
						pos2Label.setVisibility(View.VISIBLE);
						clicks2Label.setVisibility(View.VISIBLE);
						parentLabel.setVisibility(View.VISIBLE);
						
						if (parentSpinner.getCount() == 0) {
							ArrayList<SymbolDAO> symbol_list = SymbolLogic.getInstance(((ManageSymbolActivity) getActivity()).dbHelper).getM2SymbolList(((ManageSymbolActivity) getActivity()).getProfileId(),-1);
							ArrayAdapter<SymbolDAO> parentAdapter = new ArrayAdapter<SymbolDAO>(getActivity(), android.R.layout.simple_spinner_item);
							parentAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					
							SymbolDAO blank = new SymbolDAO();
							blank.setText(getString(R.string.symbol_no_parent));
							parentAdapter.add(blank);
							
							for (SymbolDAO s:symbol_list) {
								parentAdapter.add(s);
							}
							parentSpinner.setAdapter(parentAdapter);
						}
						parentSpinner.setVisibility(View.VISIBLE);
					} else {
						getArguments().putInt("m2_pos", -1);
						getArguments().putBoolean("m2", false);
						getArguments().putInt("parent", 0);
						pos2.setVisibility(View.INVISIBLE);
						clicks2.setVisibility(View.INVISIBLE);
						pos2Label.setVisibility(View.INVISIBLE);
						clicks2Label.setVisibility(View.INVISIBLE);
						parentLabel.setVisibility(View.INVISIBLE);
						parentSpinner.setVisibility(View.GONE);
					}
					listener.onModify();
					setModified(true);
				}
			});
		}
		
		//Parent Spinner
		if (currTabIndex == 0) {
			SymbolDAO parent_dao = SymbolLogic.getInstance(((ManageSymbolActivity) getActivity()).dbHelper).getSymbolById(getArguments().getInt("parent"));
			if (parent_dao != null)
				parent.setText(parent_dao.getText());
		}
		else {
			parentSpinner = (Spinner) v.findViewById(R.id.select_parent_spinner);
			if (m2.isChecked()) {
				parentSpinner.setVisibility(View.VISIBLE);
				parent.setVisibility(View.GONE);
				ArrayList<SymbolDAO> symbol_list = SymbolLogic.getInstance(((ManageSymbolActivity) getActivity()).dbHelper).getM2SymbolList(((ManageSymbolActivity) getActivity()).getProfileId(),-1);
				ArrayAdapter<SymbolDAO> parentAdapter = new ArrayAdapter<SymbolDAO>(getActivity(), R.layout.spinner_little_item);
				parentAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
				SymbolDAO blank = new SymbolDAO();
				blank.setText(getString(R.string.symbol_no_parent));
				parentAdapter.add(blank);
				
				int index_of_parent = 0;
				int id_of_parent = getArguments().getInt("parent");
				int id = getArguments().getInt("id");
				for (SymbolDAO s:symbol_list) {
					if (s.getId() != id) {
						parentAdapter.add(s);
					}
					if (s.getId() == id_of_parent) {
						index_of_parent = parentAdapter.getPosition(s);
					}
				}
				parentSpinner.setAdapter(parentAdapter);
				parentSpinner.setSelection(index_of_parent);
			}
	
			//Parent spinner listener
			parentSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
	
				@Override
				public void onItemSelected(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					if (isParentSpinnerSelectable) {
					@SuppressWarnings("unchecked")
					ArrayAdapter<SymbolDAO> adapter = (ArrayAdapter<SymbolDAO>) arg0.getAdapter();
					SymbolDAO selected_item = adapter.getItem(arg2);
					if (getArguments().getInt("parent") != selected_item.getId()) {
						//Update options instance of the symbol
						int parent_id; 
						if (selected_item.getId() < 0)
							parent_id = 0;
						else
							parent_id = selected_item.getId();
						
						getArguments().putInt("parent",parent_id);
						int new_pos = SymbolLogic.getInstance(((ManageSymbolActivity)getActivity()).dbHelper).getSymbolNumChildren(parent_id);
						getArguments().putInt("m2_pos",new_pos);
						
						//Update list
						listener.onChangeParent(getArguments().getInt("id"), parent_id);
						
						pos2.setText(String.valueOf(new_pos));
						listener.onModify();
						setModified(true);
					}
					} else {
						isParentSpinnerSelectable = true;
					}
				}
	
				@Override
				public void onNothingSelected(AdapterView<?> arg0) {}
			});
		}

		// Radio Buttons listener
		soundButton1.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					getArguments().putInt("sound_choise", 0);
					soundRecord.setVisibility(View.GONE);
					soundPlay.setImageResource(R.drawable.play_on);
					soundPlay.setClickable(true);
					tts.setText(title.getText());
				} else {
					getArguments().putInt("sound_choise", 1);
					soundRecord.setVisibility(View.VISIBLE);
					if (!getArguments().getString("sound_path").equals("")) {
						soundPlay.setImageResource(R.drawable.play_on);
						soundPlay.setClickable(true);
						tts.setText(R.string.registered);
					} else {
						soundPlay.setImageResource(R.drawable.play_off);
						soundPlay.setClickable(false);
						tts.setText(R.string.not_registered);
					}
				}
				listener.onModify();
				setModified(true);
			}
		});

		// Play listener
		soundPlay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (getArguments().getInt("sound_choise") == 0) {
					((ManageSymbolActivity) getActivity()).startSymbolSound(
							getArguments().getInt("sound_choise"), tts
									.getText().toString());
				} else {
					((ManageSymbolActivity) getActivity()).startSymbolSound(
							getArguments().getInt("sound_choise"),
							getArguments().getString("sound_path"));
				}
			}
		});

		// Record listener
		soundRecord.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				// Start activity to use defauld audio recording of Android
				Intent intent = new Intent(
						MediaStore.Audio.Media.RECORD_SOUND_ACTION);
				startActivityForResult(intent, RECORDING_INTENT);
			}
		});

		// Title listener
		title.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (soundButton1.isChecked()) {
					tts.setText(s);
					getArguments().putString("txt", s.toString());
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				listener.onModify();
				setModified(true);
			}
		});

		// Move up listener
		moveUp = (ImageButton) v.findViewById(R.id.options_up);
		moveUpLabel = (TextView) v.findViewById(R.id.options_up_label);
		if (isNewSymbol) {
			moveUp.setVisibility(View.GONE);
			moveUpLabel.setVisibility(View.GONE);
		} else {
			moveUp.setAlpha(200);
			moveUp.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					listener.onModify();
					setModified(true);
					listener.onMoveUp(getArguments().getInt("id"));
				}
			});
		}

		// Move down listener
		moveDown = (ImageButton) v.findViewById(R.id.options_down);
		moveDownLabel = (TextView) v.findViewById(R.id.options_down_label);
		if (isNewSymbol) {
			moveDown.setVisibility(View.GONE);
			moveDownLabel.setVisibility(View.GONE);
		} else {
			moveDown.setAlpha(200);
			moveDown.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					listener.onModify();
					setModified(true);
					listener.onMoveDown(getArguments().getInt("id"));
				}
			});
		}

		// Delete listener
		delete = (ImageButton) v.findViewById(R.id.delete_symbol);
		deleteLabel = (TextView) v.findViewById(R.id.delete_symbol_label);
		if (isNewSymbol) {
			delete.setVisibility(View.GONE);
			deleteLabel.setVisibility(View.GONE);
		} else {
			delete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					listener.onDelete(getArguments().getInt("id"));
				}
			});
		}

		// Save listener
		save = (ImageButton) v.findViewById(R.id.save_changes);
		save.setAlpha(30);
		save.setClickable(false);
		save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				SymbolDAO newSymbol = new SymbolDAO(
						getArguments().getInt("id"), getArguments().getString(
								"name"), getArguments().getInt("img_res"),
						title.getText().toString(), getArguments().getString(
								"img_path"), getArguments().getInt("parent"),
						getArguments().getBoolean("m1"), getArguments().getInt(
								"m1_pos"), getArguments().getBoolean("m2"),
						getArguments().getInt("m2_pos"), getArguments()
								.getString("sound_path"), getArguments()
								.getInt("profile"), getArguments().getInt(
								"sound_choise"));
				newSymbol.setClicksM1(getArguments().getInt("clicks_m1"));
				newSymbol.setClicksM2(getArguments().getInt("clicks_m2"));
				listener.onSave(newSymbol);
			}
		});

		// StartPreview listener
		startPreview = (Button) v.findViewById(R.id.start_preview);
		stopPreview = (Button) v.findViewById(R.id.stop_preview);
		surfaceView = (SurfaceView) v.findViewById(R.id.options_surface);

		startPreview.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (!isPreviewOpen) {

					image.setVisibility(View.GONE);
					surfaceView.setVisibility(View.VISIBLE);

					if (camera == null) {
						camera = Camera.open();
					}

					Parameters p = camera.getParameters();
					p.setPictureSize(1200, 600);
					p.setJpegQuality(100);
					camera.setParameters(p);

					surfaceView.getHolder().addCallback(
							new SurfaceHolder.Callback() {
								@Override
								public void surfaceDestroyed(
										SurfaceHolder holder) {
								}

								@Override
								public void surfaceCreated(SurfaceHolder holder) {
									try {
										camera.setPreviewDisplay(surfaceView
												.getHolder());
									} catch (IOException e) {
										e.printStackTrace();
									}
									camera.startPreview();
									isPreviewOpen = true;

									startPreview.setText(getResources()
											.getString(R.string.take_picture));
									stopPreview.setVisibility(View.VISIBLE);
								}

								@Override
								public void surfaceChanged(
										SurfaceHolder holder, int format,
										int width, int height) {
								}
							});
				} else {
					camera.takePicture(null, null, new PictureCallback() {

						@Override
						public void onPictureTaken(byte[] data, Camera camera) {

							ContentValues cv = new ContentValues();
							cv.put(MediaColumns.TITLE, "MindReaderSquared_("
									+ getArguments().getInt("profile") + ")");
							Uri uriTarget = getActivity().getContentResolver()
									.insert(Images.Media.EXTERNAL_CONTENT_URI,
											cv);
							OutputStream imageFileOS;
							try {
								imageFileOS = getActivity()
										.getContentResolver().openOutputStream(
												uriTarget);
								imageFileOS.write(data);
								imageFileOS.flush();
								imageFileOS.close();
							} catch (FileNotFoundException e) {
								e.printStackTrace();
							} catch (IOException e) {
								e.printStackTrace();
							}

							getArguments().putString("img_path",
									uriTarget.toString());
							getArguments().putInt("img_res", -1);

							surfaceView.setVisibility(View.GONE);
							image.setImageDrawable(((ManageSymbolActivity) getActivity())
									.getSymbolImage(
											getArguments().getInt("img_res"),
											getArguments()
													.getString("img_path")));
							image.setVisibility(View.VISIBLE);

							listener.onModify();
							setModified(true);
						}
					});

					isPreviewOpen = false;
					startPreview.setText(getResources().getString(
							R.string.start_preview));
					stopPreview.setVisibility(View.GONE);
				}
			}
		});

		// Stop preview listener
		stopPreview.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (isPreviewOpen) {
					camera.stopPreview();
					isPreviewOpen = false;
					surfaceView.setVisibility(View.GONE);
					image.setImageDrawable(((ManageSymbolActivity) getActivity())
							.getSymbolImage(getArguments().getInt("img_res"),
									getArguments().getString("img_path")));
					image.setVisibility(View.VISIBLE);
					startPreview.setText(getResources().getString(
							R.string.start_preview));
					stopPreview.setVisibility(View.GONE);
				}
			}
		});

		// Load Picture listener
		loadPicture = (Button) v.findViewById(R.id.load_picture);
		loadPicture.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (isPreviewOpen) {
					camera.stopPreview();
					isPreviewOpen = false;
					surfaceView.setVisibility(View.GONE);
					image.setImageDrawable(((ManageSymbolActivity) getActivity())
							.getSymbolImage(getArguments().getInt("img_res"),
									getArguments().getString("img_path")));
					image.setVisibility(View.VISIBLE);
					startPreview.setText(getResources().getString(
							R.string.start_preview));
					stopPreview.setVisibility(View.GONE);
				}

				listener.onLoadImage();
			}
		});

		// Load Default Image listener
		loadDefaultPicture = (Button) v.findViewById(R.id.load_default_picture);
		loadDefaultPicture.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (isPreviewOpen) {
					camera.stopPreview();
					isPreviewOpen = false;
					surfaceView.setVisibility(View.GONE);
					image.setImageDrawable(((ManageSymbolActivity) getActivity())
							.getSymbolImage(getArguments().getInt("img_res"),
									getArguments().getString("img_path")));
					image.setVisibility(View.VISIBLE);
					startPreview.setText(getResources().getString(
							R.string.start_preview));
					stopPreview.setVisibility(View.GONE);
				}

				// Find default image related to symbol name
				String image = "";
				TypedArray symbolList = getActivity().getResources()
						.obtainTypedArray(R.array.m1_symbol_list);
				TypedArray defaultImages = getActivity().getResources()
						.obtainTypedArray(R.array.m1_symbols_default_images);
				boolean trovato = false;
				for (int i = 0; i < symbolList.length() && !trovato; i++) {
					if (getArguments().getString("name").equals(
							symbolList.getString(i))) {
						image = String.valueOf(defaultImages.getResourceId(i,
								R.drawable.m1_image_not_found));
						trovato = true;
					}
				}
				setNewImage(image);
				
				symbolList.recycle();
				defaultImages.recycle();
			}
		});

		return v;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == RECORDING_INTENT && data != null) {
			getArguments().putString("sound_path", data.getData().toString());

			soundPlay.setImageResource(R.drawable.play_on);
			soundPlay.setClickable(true);
			tts.setText(R.string.registered);

			listener.onModify();
			setModified(true);
		}
	}

	// View public methods
	// This methods can be used by the activity to show or hide something in
	// this fragment.
	public void augmentPos(boolean m1) {
		if (m1) {
			if (getArguments().getBoolean("m1")) {
				int old_pos = Integer.parseInt(pos1.getText().toString());
				pos1.setText(String.valueOf(old_pos + 1));
				getArguments().putInt("m1_pos", old_pos + 1);
			}
		} else {
			if (getArguments().getBoolean("m2")) {
				int old_pos = Integer.parseInt(pos2.getText().toString());
				pos2.setText(String.valueOf(old_pos + 1));
				getArguments().putInt("m2_pos", old_pos + 1);
			}
		}
	}

	public void decreasePos(boolean m1) {
		if (m1) {
			if (getArguments().getBoolean("m1")) {
				int old_pos = Integer.parseInt(pos1.getText().toString());
				pos1.setText(String.valueOf(old_pos - 1));
				getArguments().putInt("m1_pos", old_pos - 1);
			}
		} else {
			if (getArguments().getBoolean("m2")) {
				int old_pos = Integer.parseInt(pos2.getText().toString());
				pos2.setText(String.valueOf(old_pos - 1));
				getArguments().putInt("m2_pos", old_pos - 1);
			}
		}
	}

	public void setModified(boolean modified) {
		if (modified) {
			save.setAlpha(200);
			save.setClickable(true);
		} else {
			save.setAlpha(30);
			save.setClickable(false);
		}
	}

	public void setUpLimit(boolean limitated) {
		if (limitated) {
			moveUp.setAlpha(30);
			moveUp.setClickable(false);
		} else {
			moveUp.setAlpha(200);
			moveUp.setClickable(true);
		}
	}

	public void setDownLimit(boolean limitated) {
		if (limitated) {
			moveDown.setAlpha(30);
			moveDown.setClickable(false);
		} else {
			moveDown.setAlpha(200);
			moveDown.setClickable(true);
		}
	}

	public void setNewImage(String image) {
		try {
			int i = Integer.parseInt(image);
			getArguments().putString("img_path", "");
			getArguments().putInt("img_res", i);
		} catch (NumberFormatException e) {
			getArguments().putString("img_path", image);
			getArguments().putInt("img_res", -1);
		} finally {
			this.image.setImageDrawable(((ManageSymbolActivity) getActivity())
					.getSymbolImage(getArguments().getInt("img_res"),
							getArguments().getString("img_path")));

			listener.onModify();
			setModified(true);
		}
	}
}